package persist

import (
	"context"
	"github.com/olivere/elastic"
	"log"
	"xiaoshuo/engine"
)

func ItemSaver(index string) (chan engine.Profile, error) {
	client, err := elastic.NewClient()
	if err != nil {
		return nil, err
	}
	out := make(chan engine.Profile)
	go func(){
		count := 0
		for {
			item := <- out
			log.Printf("Item Data %v", item)
			_, err := save(client, item, index)
			if err != nil {
				log.Printf("Item Saver: error saving item %v: %v", item, err)
			}
			count++
		}
	}()

	return out, nil
}


func save(client *elastic.Client,item engine.Profile, index string) (id string, err error) {
	resp, err := client.Index().Index(index).Type(item.Type).Id(item.Id).BodyJson(item).Do(context.Background())
	if err != nil {
		return "", err
	}
	return resp.Id, nil
}